package 网络编程.TCPECHO2;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-04
 * Time: 22:24
 */
public class TCPEchoClint2 {

    Socket socket = null;
    public TCPEchoClint2() throws IOException {
        socket = new Socket("127.0.0.1", 8000);
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scan = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
           while (true){
               System.out.print(">");
               //从控制台上读取请求
               String request = scan.next();
               //写入给客户端
               BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
               bufferedWriter.write(request);
               bufferedWriter.newLine();
               bufferedWriter.flush();
               //读取服务器返回的响应
               BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
               String response =bufferedReader.readLine();
               System.out.printf("req = %s;rep = %s\n",request,response);
           }
        }finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClint2 tcpEchoClint1 = new TCPEchoClint2();
        tcpEchoClint1.start();
    }

}
